﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.DBManager;
using VOL.Core.Float;
using VOL.Entity.DomainModels;
using VOL.Entity.DomainModels.eager;

namespace VOL.WebApi.Controllers.MyTable.customer_api
{
    [Route("api/test")]
    [ApiController]
    public class TestController : Controller
    {
        [HttpGet, Route("get_max"), AllowAnonymous]
        public int get_max()
        {
            var dd = DBServerProvider.DbContext.Set<cc_task>().Select(s =>s.xuh??0).Max();
            return dd;
        }
        [HttpGet, Route("test_linq_where"), AllowAnonymous]
        public dynamic test_linq_where()
        {
            //var yg_xx_list = DBServerProvider.DbContext.Set<yg_xx>().Where(w=>!string.IsNullOrEmpty(w.SHUOM_1));//亿格配置变量
            var yg_xx_list = DBServerProvider.DbContext.Set<yg_xx>().ToList();//亿格配置变量
            //Console.WriteLine(JsonConvert.SerializeObject(yg_xx_list));
            //string xuanx_z = yg_xx_list.Where(w => w.SHUOM.Trim().Contains("导流罩") && w.SHUOM_1.Contains("固定式(U+)")).Select(s => s.XUANX).FirstOrDefault();//查询字符中有特殊字符，如  旗舰+滑动
            string xuanx_z = yg_xx_list.Where(w => !string.IsNullOrEmpty(w.SHUOM_1) && w.SHUOM_1.Contains("固定式(U+)")&& w.SHUOM.Contains("导流罩")).Select(s => s.XUANX).FirstOrDefault();//查询字符中有特殊字符，如  旗舰+滑动

            return xuanx_z;
        }

        [HttpGet, Route("test_type"), AllowAnonymous]
        public dynamic test_type()
        {
            string class_name_str = "yg_xx";
           // dynamic rtn = Activator.CreateInstance(Type.GetType(class_name_str));

            return class_name_str;
        }

        [HttpGet, Route("test_FloatManager"), AllowAnonymous]
        public dynamic test_FloatManager()
        {
            Guid guid = new Guid("ABE66C42-282C-4710-AFFF-A809BE39EBC9");
            
           return FloatManager.get_pre_step(30, guid);
        }


        [HttpGet, Route("test_task_api"), AllowAnonymous]
        public dynamic test_task_api()
        {
            string s_url = "http://10.100.150.18:8181/api/cw_djlc_wlzb/get_sap_bom?P_DATUB_OUT={0}&P_MATNR_OUT={1}&newbomnumber={2}&cw_djlc_djzb_id={3}";//取BOM
            
            string ddtime = DateTime.Now.ToString("yyyyMMdd").ToString();
            List<cw_djlc_djzb> cw_djlc_djzb_list = DBServerProvider.DbContext.Set<cw_djlc_djzb>().ToList();
            Hashtable rtn_hst = new Hashtable();
            for (int i = 0; i <cw_djlc_djzb_list.Count; i++)
            { 
                //Console.WriteLine(string.Format(s_url, ddtime, cw_djlc_djzb_list[i].newmaterialnum, cw_djlc_djzb_list[i].newbomnumber,cw_djlc_djzb_list[i].cw_djlc_djzb_id));
                if (cw_djlc_djzb_list[i].synchronizationbomstatus != 1)
                {
                    string aa = string.Format(s_url, ddtime, cw_djlc_djzb_list[i].newmaterialnum, cw_djlc_djzb_list[i].newbomnumber, cw_djlc_djzb_list[i].cw_djlc_djzb_id);
                    var request = (HttpWebRequest)WebRequest.Create(aa);
                    request.Method = "POST";
                    request.ContentType = "application/json;charset=UTF-8";
                    var response = (HttpWebResponse)request.GetResponse();
                    var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                    cw_djlc_djzb_list[i].synchronizationbomstatus = 1;
                    DBServerProvider.DbContext.Update(cw_djlc_djzb_list[i]);
                    rtn_hst.Add("BOM-"+cw_djlc_djzb_list[i].newmaterialnum+"-"+cw_djlc_djzb_list[i].cw_djlc_djzb_id, responseString);
                }   
            }

            string p_url = "http://10.100.150.18:8181/api/cw_djlc_wlzb/get_sap_price_tou?P_MATNR={0}&bomnumber={1}";//取价格
            for (int i = 0; i < cw_djlc_djzb_list.Count; i++)
            {
                //Console.WriteLine(string.Format(s_url, ddtime, cw_djlc_djzb_list[i].newmaterialnum, cw_djlc_djzb_list[i].newbomnumber,cw_djlc_djzb_list[i].cw_djlc_djzb_id));
                if (cw_djlc_djzb_list[i].synchronizationpricestatus != 1)
                {
                    string aa = string.Format(p_url, cw_djlc_djzb_list[i].newmaterialnum, cw_djlc_djzb_list[i].newbomnumber);
                    var request = (HttpWebRequest)WebRequest.Create(aa);
                    request.Method = "POST";
                    request.ContentType = "application/json;charset=UTF-8";
                    var response = (HttpWebResponse)request.GetResponse();
                    var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                    cw_djlc_djzb_list[i].synchronizationpricestatus = 1;
                    DBServerProvider.DbContext.Update(cw_djlc_djzb_list[i]);
                   
                    rtn_hst.Add("PRICE-" + cw_djlc_djzb_list[i].newmaterialnum + "-" + cw_djlc_djzb_list[i].cw_djlc_djzb_id, responseString);
                }
            }

           
            DBServerProvider.DbContext.SaveChanges();

            for (int i = 0; i < cw_djlc_djzb_list.Count; i++)
            {
                batchUpdateOfJgwh(cw_djlc_djzb_list[i].cw_djlc_djzb_id.ToString());
            }
            return rtn_hst;
            //return "00";
        }
        private void batchUpdateOfJgwh(string cw_djlc_djzb_id)
        {
            var db = DBServerProvider.DbContext;
            Guid djlcId = Guid.Parse(cw_djlc_djzb_id);
            //status 0启用，1不启用
            List<cw_djlc_wljgwh> list = db.Set<cw_djlc_wljgwh>().Where(x => x.cw_djlc_djzb_id == djlcId).ToList();
            var dbcw_djlc_wljgwh = db.Set<cw_djlc_wljgwh>();
            var dbcw_djlc_wlzb = db.Set<cw_djlc_wlzb>();
            var dbcw_djlc_jgwh = db.Set<cw_djlc_jgwh>();
            foreach (var item in list)
            {
                Guid wlzbId = (Guid)item.cw_djlc_wlzb_id;
                cw_djlc_wlzb wlzb = dbcw_djlc_wlzb.Where(x => x.cw_djlc_wlzb_id == wlzbId).ToList().FirstOrDefault();
                string codename = "";
                if (wlzb != null)
                {
                    codename = wlzb.codename;
                }
                cw_djlc_jgwh jgwh = dbcw_djlc_jgwh.Where(x => x.codename == codename && x.status == 0).ToList().FirstOrDefault();
                if (jgwh != null)
                {
                    item.cw_djlc_jgwh_id = jgwh.cw_djlc_jgwh_id;
                }
                db.Update(item);
            }
            db.SaveChanges();
        }
        [HttpGet, Route("test_mysql"), AllowAnonymous]
        public dynamic test_mysql()
        {
            List<dynamic> rntlist =  MySql_Helper.query_common("select * from cd_node", "39");//读取mysql
            for (int i = 0; i < rntlist.Count; i++)
            {
                Console.WriteLine(rntlist[i].title);
                Other_Oracle_Helper.Execute("insert into aa(ca) values('" + rntlist[i].title + "')","118");//插入oracle
            }
           // Other_Oracle_Helper.Execute("delete from aa", "118");//删除数据
            return rntlist;
        }
        [HttpGet, Route("test_oracle"), AllowAnonymous]
        public dynamic test_oracle()
        {
            List<yg_xx> yg_xx_list = DBServerProvider.DbContext.Set<yg_xx>().ToList();
            string xiangm = "23100056";
            string zhuwl = "U6T4BKH044";
            string conn_yg = "118";//yige
            //List<yg_custom_bom> yg_custom_bom_list = new List<yg_custom_bom>();//自定义表-生成亿格客户BOM
            DBServerProvider.DbContext.RemoveRange(DBServerProvider.DbContext.Set<yg_custom_bom>().Where(a => a.XIANGM == xiangm));
            string ybbom_sql = "select * from tycp107 where zhuwl='"+ zhuwl+"'";//样板BOM，需要递归查询出所有的BOM组件
            string dmsxx_sql = "select * from TYCP204 where xiangm='"+xiangm+"'";//DMS传给亿格的订单选项
            var ybbom_list= Other_Oracle_Helper.query<Tycp107>(ybbom_sql, conn_yg);
            var dmsxx_list= Other_Oracle_Helper.query<Tycp204>(dmsxx_sql, conn_yg);
            for (int i = 0; i < ybbom_list.Count; i++)
            {
                yg_custom_bom ycb = new yg_custom_bom();
                string rtn_bds="";
                if (ybbom_list[i].BIAODS == "/"|| jx_single_express(ybbom_list[i].BIAODS, dmsxx_list, yg_xx_list,ref rtn_bds))
                {
                    ycb.XIANGM = xiangm;
                    ycb.KEHWL = zhuwl;
                    ycb.SHUL = ybbom_list[i].JINGSL;
                    ycb.GONGW = ybbom_list[i].GONGW;
                    ycb.HANGH = ybbom_list[i].HANGH;
                    ycb.WULIAO = ybbom_list[i].WULIAO;
                    ycb.rtn_bds = rtn_bds;
                    DBServerProvider.DbContext.Add(ycb);
                }
                
            }
            var rtn = ybbom_list;
            DBServerProvider.DbContext.SaveChanges();
            return rtn;
        }
        [HttpGet, Route("ys_process"), AllowAnonymous]
        /// <summary>
        /// 颜色件处理
        /// </summary>
        /// <param name="wulh">组件号</param>
        /// <param name="z_ce_wulhao">整车头物料号</param>
        /// <returns></returns>
        public dynamic ys_process(string wulh,string z_ce_wulhao)
        {
            //string rtn_wulh = wulh;
            string rtn_wulh = "100392100136";
            string z_ce_wulhao1 = "U6T4BNH214012R00";
            string sql1 = @"select a.*, b.*
                              from tyjcdlst a, tyjcdict b
                             where a.zhidlb = b.zhidlb
                               and 'A' || substr(substr('@z_ce_wulhao1@', -3), 1, 1) = b.zhidxh
                               and a.zhidlb in
                                   (select zhidxh
                                      from tyjcdict
                                     where zhidlb =
                                           (select zhidlb
                                              from tyjcdlst
                                             where leibsm =
                                                   (select shuom
                                                      from JRLH_WULIAOYS, tyjcdict
                                                     where wuliao = '@rtn_wulh@'
                                                       and JRLH_WULIAOYS.GROUPID = tyjcdict.zhidxh
                                                       and tyjcdict.zhidlb = '80003')))";
            sql1 = sql1.Replace("@rtn_wulh@", rtn_wulh).Replace("@z_ce_wulhao1@", z_ce_wulhao1);
            List<dynamic> rows=Other_Oracle_Helper.query_common(sql1, "yige");
            /*foreach (dynamic row in rows)
            {
                Console.WriteLine(row.GROUPID);//Dapper Row类型的取数方式，注意字段大小写是有区别的
            }*/
            if (rows[0].GROUPID =="108"&& rows.Count>0)
            {
                Console.WriteLine(rows[0].GROUPID);
            }
           // string rtn = rows;
            
            return rows;
        }
        bool jx_single_express(string biaods,List<Tycp204> dmsxx_list, List<yg_xx> yg_xx_list,ref string rtn_bds)
        {
            //bool rtn = false;
            rtn_bds = "";
            string biaods_t = biaods;
            if (!string.IsNullOrEmpty(biaods) && biaods != "/")
            {

                // biaods_t = biaods_t
                for (int i = 0; i < dmsxx_list.Count; i++)
                {
                    biaods_t = biaods_t.Replace(dmsxx_list[i].TEZM, dmsxx_list[i].TEZXJ);
                }
                for (int i = 0; i < yg_xx_list.Count; i++)
                {
                    biaods_t = biaods_t.Replace(yg_xx_list[i].XUANX, "'"+ yg_xx_list[i].XUANX +"'");
                }
                biaods_t = biaods_t.Replace("{", "(").Replace("}", ")");
                rtn_bds = biaods_t;
                string pd_sql = "select * from Sys_User where " + biaods_t;
                List<dynamic> rnt_list = DBServerProvider.SqlDapper.QueryList<dynamic>(pd_sql, "").ToList();
                if (rnt_list.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
               // Console.WriteLine(biaods_t);
            }
            else
            {
                return true;
            }
            
            //return rtn;
        }

        /*    private async Task<string> batchUpdateOfJgwh(string cw_djlc_djzb_id)
        {
            return await Task.Run(() =>
            {
                using (var db = DBServerProvider.DbContext)
                {
                    Guid djlcId = Guid.Parse(cw_djlc_djzb_id);
                    //status 0启用，1不启用
                    List<cw_djlc_wljgwh> list = db.Set<cw_djlc_wljgwh>().Where(x => x.cw_djlc_djzb_id == djlcId).ToList();
                    var dbcw_djlc_wljgwh = db.Set<cw_djlc_wljgwh>();
                    var dbcw_djlc_wlzb = db.Set<cw_djlc_wlzb>();
                    var dbcw_djlc_jgwh = db.Set<cw_djlc_jgwh>();
                    foreach (var item in list)
                    {
                        Guid wlzbId = (Guid)item.cw_djlc_wlzb_id;
                        cw_djlc_wlzb wlzb = dbcw_djlc_wlzb.Where(x => x.cw_djlc_wlzb_id == wlzbId).ToList().FirstOrDefault();
                        string codename = "";
                        if (wlzb != null)
                        {
                            codename = wlzb.codename;
                        }
                        cw_djlc_jgwh jgwh = dbcw_djlc_jgwh.Where(x => x.codename == codename && x.status == 0).ToList().FirstOrDefault();
                        if (jgwh != null)
                        {
                            item.cw_djlc_jgwh_id = jgwh.cw_djlc_jgwh_id;
                        }
                        db.Update(item);
                    }
                    db.SaveChanges();

                }
                return "1";
            });
                //return 1;

        }*/
    }

}
